<?php
namespace app\service;

use think\Cache;

class RedisQueue
{
    protected $redis;
    protected $prefix = '';
    
    public function __construct()
    {
        $this->redis = Cache::store('redisQueue')->handler();
    }
    
    /**
     * 入队
     * @param string $queueName 队列名称
     * @param mixed $data 数据
     * @return bool|int
     */
    public function push($queueName, $data)
    {
        if (is_array($data)) {
            $data = json_encode($data);
        }
        return $this->redis->lPush($this->prefix.$queueName, $data);
    }
    
    /**
     * 出队
     * @param string $queueName 队列名称
     * @return mixed
     */
    public function pop($queueName)
    {
        $data = $this->redis->rPop($this->prefix.$queueName);
        return json_decode($data, true) ?: $data;
    }
    
    /**
     * 获取队列长度
     * @param string $queueName 队列名称
     * @return int
     */
    public function length($queueName)
    {
        return $this->redis->lLen($this->prefix.$queueName);
    }
    
    /**
     * 获取队列所有元素(不删除)
     * @param string $queueName 队列名称
     * @return array
     */
    public function all($queueName)
    {
        $items = $this->redis->lRange($this->prefix.$queueName, 0, -1);
        return array_map(function($item) {
            return json_decode($item, true) ?: $item;
        }, $items);
    }
}